<?php

class Backend_Designer_Sub_Project extends Backend_Designer_Sub
{
	
	public function checkloadedAction()
	{
		if($this->_session->keyExists('loaded') && $this->_session->get('loaded'))
		{
			
			Response::jsonSuccess();
		}
		else 
		{
			Response::jsonError();
		}
	}
	/**
	 * Load project
	 */
	public function loadAction()
	{
		$file = Request::post('file', 'string', false);
	
		try{	
			$project = $this->_storage->load($file);
		}catch (Exception $e){;
			Response::jsonError($this->_lang->WRONG_REQUEST);
		}
		
		$this->_session->set('loaded' , true);
		$this->_session->set('project' , $project);
		$this->_session->set('file' , $file);
		
		Response::jsonSuccess();
	}
	
	/**
	 * Clear report session
	 */
	public function closeAction()
	{
		$this->_session->remove('loaded');
		$this->_session->remove('project');
		$this->_session->remove('file');
		Response::jsonSuccess();	
	}
	
	/**
	 * Save report
	 */
	public function saveAction()
	{		
		$this->_checkLoaded();
			
		if($this->_storage->save($this->_session->get('file'), $this->_session->get('project')))
			Response::jsonSuccess();
		else 
			Response::jsonError($this->_lang->CANT_EXEC);		
	}
	/**
	 * Get project config
	 */
	public function loadconfigAction()
	{
		$this->_checkLoaded();
		Response::jsonSuccess($this->_getProject()->getConfig());
	}
	/**
	 * Set project config option
	 */
	public function setconfigAction(){
		$project = $this->_getProject();
		$names = array_keys($project->getConfig());
		foreach ($names as $name){
			$value = Request::post($name, 'string', false);
			if($value!==false)
				$project->$name = $value;
		}
		Response::jsonSuccess();
	}
	/**
	 * Add object to the project tree
	 */
	public function addobjectAction()
	{
		$this->_checkLoaded();
		$name = Request::post('name', 'alphanum', false);
		$class = Request::post('class', 'alphanum', false);
		$parent = Request::post('parent', 'alphanum', 0);
		
		$project = $this->_getProject();
		
		if(!strlen($parent))
			$parent = 0;
			
		if(!$name || !$class)
			Response::jsonError($this->_lang->WRONG_REQUEST);
			
		if($project->objectExists($name))
			Response::jsonError($this->_lang->SB_UNIQUE);

		$class = ucfirst($class);	
		$className = 'Ext_Object_' . ucfirst($class);	
			
		if(class_exists($className))
			$object = new $className();
		else 
			$object = new Ext_Object_Virtual($class);
			
		$object->setName($name);
		$project->addObject($parent, $object);
		
		$this->_storeProject();
		
		Response::jsonSuccess();	
	}
}